<style lang="scss" scoped>
.sample-inner {
    padding: 10px 30px;
    .tables.ivu-col {
        display: flex;
        .ivu-form-item {
            flex: 1;
            .ivu-date-picker {
                width: 100%;
            }
        }
        .ivu-form-item+.ivu-form-item {
            margin-left: 20px;
        }
    }
}

.handle {
    width: 600px;
    margin: auto;
    button {
        padding: 6px 40px;
    }
    button:nth-of-type(1) {
        float: left;
    }
}

.upload {
    overflow: hidden;
}


</style>
<template>
    <div>
        <!-- 样本信息 -->
        <Modal v-model="modalShow" width="835px" title="样本信息（*为必填项）" :mask-closable="false" @on-cancel='closeModal()'>
            <div class="sample-inner">
                <Form :model="sampleInfo" ref="sampleInfo" label-position="right" :label-width="100" inline :rules="ruleCustom">
                    <Row>
                        <Col class="tables">
                        <FormItem label="样本编号" prop="samplecode">
                            <Input v-model="sampleInfo.samplecode" :disabled='disEdit'></Input>
                        </FormItem>
                        <FormItem label="是否患病" prop="patientsate">
                            <Select v-model="sampleInfo.patientsate">
                                <Option value="">请选择</Option> 
                                <Option value="affected">是</Option>
                                <Option value="unaffected">否</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col class="tables">
                        <FormItem label="亲属关系" prop="designator">
                            <Select v-model="sampleInfo.designator">
                                <Option v-for="item in designator" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                  
                        <FormItem label="测序类型" prop="region">
                            <Select v-model="sampleInfo.region">
                                <Option v-for="item in region" :value="item.value" :key="item.value" :disabled="item.disabled">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col class="tables">
                        <FormItem label="样本类型">
                            <Select v-model="sampleInfo.sampletype">
                                <Option v-for="item in sampletype" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="收样日期">
                            <DatePicker type="date"  v-model="receivedate" format="yyyy-MM-dd" @on-change="time2"></DatePicker>
                        </FormItem>
                        </Col>
                        <Col class="tables">
                        <FormItem label="测序日期">
                            <DatePicker type="date"  v-model="seqdate" format="yyyy-MM-dd" @on-change="time3"></DatePicker>
                        </FormItem>
                        <FormItem label="取样日期">
                            <DatePicker type="date"  v-model="takendate" format="yyyy-MM-dd" @on-change="time1"></DatePicker>
                        </FormItem>
                        </Col>
                        <Col class="tables">
                            <FormItem label="测序平台">
                            <Input v-model="sampleInfo.platformId"></Input>
                        </FormItem>
                        <FormItem label="Enrichment Kit">
                            <Input v-model="sampleInfo.enrichmentkitId"></Input>
                        </FormItem>
                        </Col>
                        <Col class="tables">
                        <FormItem label="样本批次" prop="samplebatch">
                            <Input v-model="sampleInfo.samplebatch"></Input>
                        </FormItem>
                        <FormItem label="备注">
                            <Input v-model="sampleInfo.notes"></Input>
                        </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div slot="footer" class="handle">
                <Button type="primary" @click="keepInfo('sampleInfo')">保存</Button>
                <Button type="primary" :disabled="upState" @click="upload">上传</Button>
            </div>
        </Modal>
        <!-- 文件上传 -->
        <Modal width="835px" class="uploadModel" v-model="upModal" :mask-closable="false" @on-cancel="closeModal" title="文件上传">
            <div class="upload">
                <Col span="24" class="demo-tabs-style2">
                <Tabs type="card" @on-click="serverlocal" v-model="tabsVal">
                     <TabPane label="本地上传" name="upload">
                            <Upload ref="upload" multiple :action='urls' :headers="{'Authorization':this.$store.state.token}" show-upload-list :data="{'sampleid':this.samid,'userId':this.userId,'type':'vcf'}" :on-success="upsuccess" :on-error="uperror">
                                <Button type="ghost" style="background:#4578ad;color:#fff;">上传文件</Button>
                            </Upload>
                    </TabPane> 

                     <!-- <TabPane label="硬盘上传" name="local">
                        <tree-grid :columns="columns" @ups='upsud' ref="tree" :tree-structure="true" :data-source="fileCategoryList" :requestUrl="samid">
                        </tree-grid>
                    </TabPane>  -->

                    <!-- 服务器上传tab -->
                     <!-- <TabPane label="服务器上传" name="server">
                        <div class="fun"></div>
                        <tree-grid :columns="columns" @ups='upsud' ref="tree" :tree-structure="true" :data-source="fileServerCategoryList" :requestUrl="samid">
                        </tree-grid>
                    </TabPane>  -->
                    <!-- 服务器上传tab结束 -->
                    <!--对象存储OSS-->
                    <!-- <TabPane label="oss上传" name="oss">
                        <div class="fun"></div>
                        <oss :sampleid="samid"></oss>
                    </TabPane> -->
                </Tabs>
                </Col>

            </div>
            <div slot="footer"></div>
        </Modal>
    </div>
</template> 
<script>
import { apiUrl, filePath } from '@/common/js/Base.js'
import { congenica } from 'api/index.js'
import { setCookie, getCookie, delCookie } from '@/common/js/cookie.js';
import treeGrid from '@/components/treeTable/vue2/TreeGrid'
import oss from '@/components/oss';
export default {
    name: 'sampleInfo',
    props: ['message'],
    data() {
        const validateSamplecode = (rule, value, callback) => {
            console.log(rule, value, callback)
            if (value === ''|| value == undefined) {
                callback(new Error('样本编号不能为空'));
            } else if (value.indexOf(" ") != -1) {
                callback(new Error('样本编号不能有空格'));
            } else if((/[\u4E00-\u9FA5]/i.test(value))){
                callback(new Error('样本编号不能含有中文'));
            }else{
                callback()
            }
        };
        const validateSamplebatch = (rule, value, callback) => {
            if (value === '0') {
                callback(new Error('样本批次不能为0'));
            } else {
                callback();
            }
        };
        return {
            patientsateTrue:true,
            patientsateFalse:false,
            urls: '',
            samid: '',
            userId: '',
            receivedOpt: {},
            takenOpt: {},
            seqOpt: {},
            sampletype: [{  //样本类型
                value: '血样',
                label: '血样'
            }, {
                value: '肿瘤活检',
                label: '肿瘤活检'
            }, {
                value: '口腔',
                label: '口腔'
            }],
            takendate: '',
            receivedate: '',
            seqdate: '',
            platform: [],
            enrichmentkit: [],
            sampleInfo: {//样本信息
                samplecode:"",
                customTemplate:''
            },            
            modalShow: true,           //窗口显示
            upModal: false,              //上传窗口
            disEdit: false,            //样本编号禁用
            states: '',                //状态保存
            upState: true,            //上传按钮状态
            fileCategoryList: [],                // 本地
            fileServerCategoryList: [],          // 服务
            ruleCustom: {
                samplecode: [{ required: true,validator: validateSamplecode, trigger: 'blur' }],
                designator: [{ required: true, message: '亲属关系不能为空', trigger: 'blur' }],
                region: [{ required: true, message: '测序类型不能为空', trigger: 'blur' }],
                samplebatch: [{ validator: validateSamplebatch, trigger: 'blur' }],
                patientsate:[{ required: true,message: '是否患病不能为空', trigger: 'change' }],
            },
            columns: [
                {
                    text: '文件名称',
                    dataIndex: 'filename',
                    width: '40%'
                },
                {
                    text: '文件大小',
                    dataIndex: 'size',
                    width: '10'
                }
            ],
            designator: [{
                value: '先证者',
                label: '先证者'
            }, {
                value: '父亲',
                label: '父亲'
            }, {
                value: '母亲',
                label: '母亲'
            }, {
                value: '兄弟',
                label: '兄弟'
            }, {
                value: '姐妹',
                label: '姐妹'
            }, {
                value: '祖父',
                label: '祖父'
            }, {
                value: '祖母',
                label: '祖母'
            }, {
                value: '外祖父',
                label: '外祖父'
            }, {
                value: '外祖母',
                label: '外祖母'
            }, {
                value: '舅舅',
                label: '舅舅'
            }, {
                value: '姨妈',
                label: '姨妈'
            }, {
                value: '叔叔',
                label: '叔叔'
            }, {
                value: '姑姑',
                label: '姑姑'
            }, {
                value: '同卵双胞胎',
                label: '同卵双胞胎'
            }, {
                value: '异卵双胞胎',
                label: '异卵双胞胎'
            }, {
                value: '其他',
                label: '其他'
            }],
            region: [{
                value: 'WES',
                label: 'WES',
                disabled: false
            }, {
                value: 'WGS',
                label: 'WGS',
                disabled: true
            }, {
                value: 'Panel',
                label: 'Panel',
                disabled: true
            }],
            tabsVal: 'upload'
        }
    },
    methods: {
        setDisabledOpt() {
            this.setReceivedOpt();
            this.setTakenOpt();
            this.setSeqOpt();
        },
        //设置收样日期不可选
        setReceivedOpt() {
            let that = this;
            this.receivedOpt = {
                disabledDate(date) {
                    if (that.takendate) {
                        if (that.seqdate) {
                            return date.valueOf() <= new Date(that.takendate).valueOf() - 86400000 || date.valueOf() > new Date(that.seqdate).valueOf();
                        } else {
                            return date.valueOf() <= new Date(that.takendate).valueOf() - 86400000 || date.valueOf() > Date.now();
                        }
                    } else if (that.$store.state.birthday) {
                        if (that.seqdate) {
                            return date.valueOf() <= new Date(that.$store.state.birthday).valueOf() - 86400000 || date.valueOf() > new Date(that.seqdate).valueOf();
                        } else {
                            return date.valueOf() <= new Date(that.$store.state.birthday).valueOf() - 86400000 || date.valueOf() > Date.now();
                        }
                    } else {
                        if (that.seqdate) {
                            return date.valueOf() > new Date(that.seqdate).valueOf();
                        } else {
                            return date.valueOf() > Date.now();
                        }
                    }
                }
            }
        },
        //设置取样日期不可选
        setTakenOpt() {
            let that = this;
            this.takenOpt = {
                disabledDate(date) {
                    if (that.$store.state.birthday) {
                        if (that.receivedate) {
                            return date.valueOf() <= new Date(that.$store.state.birthday).valueOf() - 86400000 || date.valueOf() > new Date(that.receivedate).valueOf();
                        } else if (that.seqdate) {
                            return date.valueOf() <= new Date(that.$store.state.birthday).valueOf() - 86400000 || date.valueOf() > new Date(that.seqdate).valueOf();
                        } else {
                            return date.valueOf() <= new Date(that.$store.state.birthday).valueOf() - 86400000 || date.valueOf() > Date.now();
                        }
                    } else {
                        if (that.receivedate) {
                            return date.valueOf() > new Date(that.receivedate).valueOf();
                        } else if (that.seqdate) {
                            return date.valueOf() > new Date(that.seqdate).valueOf();
                        } else {
                            return date.valueOf() > Date.now();
                        }
                    }
                }
            }
        },
        //设置测序日期不可选
        setSeqOpt() {
            let that = this;
            this.seqOpt = {
                disabledDate(date) {
                    if (that.receivedate) {
                        return date.valueOf() <= new Date(that.receivedate).valueOf() - 86400000 || date.valueOf() > Date.now();
                    } else if (that.takendate) {
                        return date.valueOf() <= new Date(that.takendate).valueOf() - 86400000 || date.valueOf() > Date.now();
                    } else if (that.$store.state.birthday) {
                        return date.valueOf() <= new Date(that.$store.state.birthday).valueOf() - 86400000 || date.valueOf() > Date.now();
                    } else {
                        return date.valueOf() > Date.now();
                    }
                }
            }
        },
        upsud() {
            this.$emit('upsuccess')
        },
        time1(e) {
            this.takendate = e;
            this.setReceivedOpt();
            this.setSeqOpt();
        },
        time2(e) {
            this.receivedate = e;
            this.setTakenOpt();
            this.setSeqOpt();
        },
        time3(e) {
            this.seqdate = e;
            this.setReceivedOpt();
            this.setTakenOpt();
        },
        // 获得服务
        _getServerDataList() {
            let obj = {
                "path": filePath.path.server,
                "userId": getCookie("userid"),
                "productId": this.$store.state.productId,
                "type": "2"
            }
            congenica.getSingleForldList(obj).then((data) => {
                if (data.returnCode == 0 || data.returnCode == 200) {
                    if (M.isArray(data.data)) {
                        this.fileServerCategoryList = data.data;
                    }
                } else if (data.returnCode == 422 || data.returnCode == 204) {
                    this.$router.push('/login')
                } else {
                    this.$Message.error(data.msg)
                }
            })
        },
        // 上传失败
        uperror(error, file, fileList) {
            console.log(error)
            this.$Message.error(error.msg)
        },
        // 上传成功
        upsuccess(response, file, fileList) {
            console.log(response);
            if (response.returnCode == 0 || response.returnCode == 200) {
                this.$Message.success(response.msg);
                $(".ivu-upload-list").find("li").last().append($('<span style= "float:right;margin-right: 10px;color:#3CBB96;" >' + response.msg + '</span>'));
                this.$emit('upsuccess')
            } else {
                this.$Message.error(response.msg);
                this.$refs.upload.clearFiles();
            }

        },
        // tabs切换事件
        serverlocal(name) {  //serverlocal
            if (name == 'local') {
                this._getLocalDataList();
            } else if (name == 'server') {
                this._getServerDataList();
            }
        },
        // 获得本地
        _getLocalDataList() {
            let obj = {
                "path": filePath.path.local,
                "userId": getCookie("userid"),
                "productId": this.$store.state.productId,
                "type": "2"
            }
            congenica.getSingleForldList(obj).then((data) => {
                // console.log(data)
                if (data.returnCode == 0 || data.returnCode == 200) {
                    if (M.isArray(data.data)) {
                        this.fileCategoryList = data.data;

                    }
                    this.loading = false;
                } else if (data.returnCode == 422 || data.returnCode == 204) {
                    this.$router.push('/login')
                } else {
                    this.$Message.error(data.msg)
                    this.loading = false;
                }
            })
        },
        //上传
        upload() {
            this.modalShow = false;
            this.upModal = true;
        },
        //关闭弹层
        closeModal() {
            this.disEdit = false;
            this.sampleInfo = {};
            this.modalShow = false;
            this.$emit('modalshowEvent')
        },
        //点击保存
        keepInfo(info) {
            let obj = {
                userId: getCookie("userid"),
                patientid: this.$store.state.patientid,
                enrichmentkit: this.enrichmentkitId,
                platform: this.platformId,
                takendate: String(this.takendate),
                receivedate: String(this.receivedate),
                seqdate: String(this.seqdate)
            }
            $.extend(this.sampleInfo, obj)
            console.log(this.sampleInfo)
            console.log(this.disEdit)
            this.$refs[info].validate((valid) => {
                if (valid) {
                    if (!this.disEdit) {
                        congenica.addSample(this.sampleInfo).then((res) => {
                            if (res.returnCode == 0 || res.returnCode == 200) {
                                this.samid = res.data.sampleid;
                                this.userId = res.data.userid;
                                this.$Message.success(res.msg);
                                this.upState = false;
                                this.$emit('keepInfos');
                            } else {
                                this.$Message.error(res.msg);
                            }
                        })
                    }
                    else {
                        congenica.updateSample(this.sampleInfo).then((res) => {
                            if (res.returnCode == 0 || res.returnCode == 200) {
                                this.$Message.success(res.msg);
                                this.$emit('keepInfos');
                            } else {
                                this.$Message.error(res.msg);
                            }
                        })
                    }
                }
            })
        },
        //获取tgex参数
        getTGexPara() {
            data.getTGexPara().then((res) => {
                console.log(res)
            })
        },
        // 获得服务上传列表
        _getForldList() {
            let obj = {
                "path": filePath.path.server,
                "userId": getCookie("userid"),
                "productId": this.$store.state.productId,
                "type": "1"
            }
            congenica.getSingleForldList(obj).then((data) => {
                console.log(data)
                if (data.returnCode == 0 || data.returnCode == 200) {
                    if (data.data.length > 0 && M.isArray(data.data)) {
                        this.localFileCategoryList = data.data;
                    }
                    this.loading = false;
                } else if (data.returnCode == 422 || data.returnCode == 204) {
                    this.$router.push('/login')
                } else {
                    this.$Message.error(data.msg)
                    this.loading = false;
                }

            }).catch((err) => {
                this.loading = false;
            })
        },
        // 获得硬盘列表
        _getServerList() {
            let obj = {
                "path": filePath.path.local,
                "userId": getCookie("userid"),
                "productId": this.$store.state.productId,
                "type": "1"
            }
            congenica.getSingleForldList(obj).then((data) => {
                console.log(data)
                if (data.returnCode == 0 || data.returnCode == 200) {
                    if (data.data.length > 0 && M.isArray(data.data)) {
                        this.fileCategoryList = data.data || [];
                    }
                    this.loading = false;
                } else if (data.returnCode == 422 || data.returnCode == 204) {
                    this.$router.push('/login')
                } else {
                    this.$Message.error(data.msg)
                    this.loading = false;
                }
            }).catch((err) => {
                this.loading = false;
            })
        },
    },
    mounted() {
        let that = this;
        // this.taken = {
        //     disabledDate(date) {
        //         const disabledDay = new Date(that.$store.state.birthday).valueOf();
        //         console.log(new Date(that.$store.state.birthday))
        //         console.log(date.valueOf())
        //         console.log(disabledDay)
        //         console.log(new Date(date))
        //         console.log(disabledDay-date.valueOf())
        //         return date && (date.valueOf() > Date.now()  || date.valueOf() <= disabledDay);
        //     }
        // }
        this.setDisabledOpt();
        this.urls = apiUrl.rare + 'congenicahelper/file/fileUpload'
        console.log(this.urls);
        this.modalShow = true;
        this.states = this.message.handle;
        console.log(this.message.sampleInfo)
        if (this.message.sampleInfo.samplebatch === '0') {
            this.message.sampleInfo.samplebatch = ''
        }
        this.sampleInfo = this.message.sampleInfo;
        switch (this.message.handle) {
            case 'add':
                this.disEdit = false;
                this.upState = true;
                break;
            case 'edit':
                this.disEdit = true;
                this.upState = false;
                this.takendate = this.sampleInfo.takendate;
                this.receivedate = this.sampleInfo.receivedate;
                this.seqdate = this.sampleInfo.seqdate;
                this.samid = this.sampleInfo.sampleid;
                this.userId = this.sampleInfo.userid;
                break;
        }
    },
    components: {
        treeGrid,
        oss
    }
}
</script>

